﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Arquitetura
{
	public class LogHelper
	{
		private static string path = string.Empty;

		public static void LogMessage( string message, string logPath )
		{
			path = logPath;

			if( createCompressFile() )
			{
				compress();
			}

			writerInFile( message );
		}

		private static bool createCompressFile()
		{
			if( !File.Exists( path ) )
			{
				return false;
			}

			FileInfo fileInfo = new FileInfo( path );
			return !fileInfo.CreationTime.Equals( DateTime.Now );
		}

		private static string getCompressFileName( FileInfo fileInfo )
		{
			return fileInfo.DirectoryName + fileInfo.Name.Split( '.' )[ 0 ];
		}

		private static void compress()
		{
			FileInfo fileInfo = new FileInfo( path );

			using( FileStream originalFileStream = File.OpenRead( path ) )
			{
				using( FileStream compressedFileStream = File.Create( getCompressFileName( fileInfo ) + "_" + fileInfo.CreationTime.Day + "_" + fileInfo.CreationTime.Month + "_" + fileInfo.CreationTime.Year + Guid.NewGuid() + ".gz" ) )
				{
					using( GZipStream compressionStream = new GZipStream( compressedFileStream, CompressionMode.Compress ) )
					{
						originalFileStream.CopyTo( compressionStream );
						originalFileStream.Flush();
						originalFileStream.Close();
						fileInfo.Refresh();
						fileInfo.Delete();
						fileInfo.Refresh();
					}
				}
			}
		}

		private static void writerInFile( string message )
		{
			StreamWriter arquivo = new StreamWriter( path, true );
			arquivo.AutoFlush = true;
			arquivo.WriteLine( message + System.Environment.NewLine );
			arquivo.Flush();
			arquivo.Close();
		}
	}
}
